//
//  FriendPhotoViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/5.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "FriendPhotoViewController.h"
#import "MemberRoamingCell.h"
#import "BusinessService+FJ.h"
#import "XAFirstCollectionViewCell.h"
#import "AddFileViewController.h"
#import "XhwAddPhotoCellCollectionViewCell.h"
@interface FriendPhotoViewController ()<BaseCollectionDelegate,UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, AddFileVCDelegate, XAFirstCollectionViewCellDelegate, UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet BaseCollection *collection;

@property (strong, nonatomic) NSString *requestedFid;

@property(nonatomic, strong) AddFileViewController *addFileVC;

/** 当前cell是否正处于长按编辑状态 */
@property (nonatomic) BOOL cellIsEditing;

//@property (nonatomic, strong) NSIndexPath *deleteIndexPath;
@property (strong, nonatomic) DTModel *deleteModel;
@property (nonatomic, strong) NSIndexPath *deleteIndexPath;
@property (nonatomic,assign) NSInteger isCurrentPlayingIndex;

@end

@implementation FriendPhotoViewController
{
    NSMutableArray <DTModel *> *data;
    UILabel *notlabel;
    
    MPMoviePlayerController *moviePlayer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _collection.bdelegate = self;
     data = [[NSMutableArray alloc]init];
    _collection.bounces = YES;
    [_collection registerNib:[UINib nibWithNibName:@"XAFirstCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"XAFirstCollectionViewCell"];
//    _collection.scrollEnabled = NO;
    [_collection registerNib:[UINib nibWithNibName:@"XhwAddPhotoCellCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"XhwAddPhotoCellCollectionViewCell"]; //xhw2018-3-7加
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initData:) name:@"refreshData" object:nil];
}
-(void)initData:(int)index{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:_model.uid forKey:@"fid"];
    dic[@"page"] = @(index);
    _requestedFid = _model.uid;
    [[BusinessService shareInstance]getalbum_list:dic success:^(id result) {
        data = [_collection result:result olddata:data index:index];
        
        if (index == 1) {
            if ([_requestedFid isEqualToString:AppDelegate.shareDelegate.user.uid]) {
                DTModel *addedModel = [[DTModel alloc] init];
                [data insertObject:addedModel atIndex:0];
            }
        }
        
        if (notlabel) {
            [notlabel removeFromSuperview];
        }
        notlabel = (UILabel *)[_collection notData];
        if (data.count == 0) {
            [self.view addSubview:notlabel];
        }
        [_collection reloadData];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)sectio{
    return data.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (indexPath.row == 0) {
//        
//         XAFirstCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XAFirstCollectionViewCellID" forIndexPath:indexPath];
//        
//        
//        return cell;
//    }else{
//        MemberRoamingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MemberRoamingCell" forIndexPath:indexPath];
//    
//        DTModel *model = [data objectAtIndex:indexPath.row];
//        if ([model.iskuaipai isEqualToString:@"1"]) {
//            cell.lable.hidden = NO;
//        }
//    
//    
//    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.path]
//                placeholderImage:[UIImage imageNamed:@"notimgs"]];
//        return cell;
//    }
    
    DTModel *model = [data objectAtIndex:indexPath.item];
    XAFirstCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XAFirstCollectionViewCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.model = model;
//    cell.deletePath = indexPath;
    cell.userID = _requestedFid;
    cell.path = indexPath;
    if ([_requestedFid isEqualToString:AppDelegate.shareDelegate.user.uid] && indexPath.item == 0) {
//        cell.deleteBtn.hidden = YES;
//
//        cell.imageView.image = [UIImage imageNamed:@"添加图标"];
        XhwAddPhotoCellCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XhwAddPhotoCellCollectionViewCell" forIndexPath:indexPath];
        cell.imageView.image = [UIImage imageNamed:@"添加图标"];
        return cell;
    } else {
        cell.deleteBtn.hidden = _cellIsEditing ? NO : YES;
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.path] placeholderImage:[UIImage imageNamed:@"notimgs"]];
    }
    
    if (model.iskuaipai.integerValue == 1) {
        cell.label.hidden = NO;
    } else {
        cell.label.hidden = YES;
    }
    //说明是视频不是图片 1代表图片 2代表视频
    if (model.isimg.intValue == 2) {
        
    }
    return cell;
    
}

#pragma mark - <XAFirstCollectionViewCellDelegate>
//- (void)willDeleteACellWithModel:(DTModel *)model {
//    _deleteModel = model;
//    [self requestDeletePhotoWithPhotoID:model.id];
//}

- (void)willDeleteACellWithModel:(DTModel *)model path:(NSIndexPath *)indexpath {
    _deleteModel = model;
    [self requestDeletePhotoWithPhotoID:model.dynamicid];
//    [self willDeleteACellAtIndexPath:indexpath];
}

- (void)willDeleteACellAtIndexPath:(NSIndexPath *)path {
    _deleteIndexPath = path;

    //从资源数组中移除该数据
    [data removeObjectAtIndex:path.item];
    [self.collection reloadData];
}

- (void)willShowAllDeleteBtn {
    self.cellIsEditing = YES;
    [self.collection reloadData];
}

- (void)willDismissAllDeleteBtn {
    self.cellIsEditing = NO;
    [self.collection reloadData];
}

- (void)requestDeletePhotoWithPhotoID:(NSString *)photoID {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];
    [dic setObject:photoID forKey:@"id"];
    NSMutableArray *imgdata =[[NSMutableArray alloc]init];
//    if (imageData) {
//        NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
//        [dici setObject:@"images" forKey:@"key"];
//        [dici setObject:imageData forKey:@"value"];
//        [imgdata addObject:dici];
//    }
    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:deleteAlbumUrl postParems:dic data:imgdata];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCRE_WIDTH - 2) / 2.0, (SCRE_WIDTH - 2) / 2.0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 2;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"didSelectItemAtIndexPath:%@",indexPath);

    if (self.cellIsEditing) {
        self.cellIsEditing = NO;
        [self.collection reloadData];
    } else {
        if ([_requestedFid isEqualToString:AppDelegate.shareDelegate.user.uid] && indexPath.item == 0) {
            if (![AppDelegate shareDelegate].islod) {
                [AppDelegate shareDelegate].islod = YES;
                
                [self.mainVC presentViewController:self.addFileVC animated:YES completion:nil];
            }
        } else {
            DTModel *msg = [data objectAtIndex:indexPath.item];

            NSString *url = msg.path;
            if (![ValidateHelper isHttpHead:url]) {
                url = [NSString stringWithFormat:@"%@%@",img_Url,url];
            }
            if (url.length > 0) {
                if([url rangeOfString:@"mp4"].location !=NSNotFound){//
                    self.isCurrentPlayingIndex = indexPath.row;
                    [self Plays:url];
                }else{
                    [self EnlargePicAction:data currentIndexPath:indexPath];
                }}
        }

    }
}

#pragma mark 视频播放
-(void)Plays:(NSString *)not{
    NSURL *url = [NSURL URLWithString:not];
    moviePlayer = [ValidateHelper bofang:url];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:moviePlayer.view];
    UISwipeGestureRecognizer *swipGestureLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                          action:@selector(swipGestureHandler:)];
    swipGestureLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [moviePlayer.view addGestureRecognizer:swipGestureLeft];
    UISwipeGestureRecognizer *swipGestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                                           action:@selector(swipGestureHandler:)];
    swipGestureRight.direction = UISwipeGestureRecognizerDirectionRight;
    [moviePlayer.view addGestureRecognizer:swipGestureRight];

    self.navigationController.navigationBarHidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
}

#pragma  mark 视频播放注销监听
- (void)playVideoFinished:(NSNotification *)theNotification{
    // 取消监听
    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter]
     removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
    // 将视频视图从父视图中删除
    [moviePlayer.view removeFromSuperview];
}

- (void)swipGestureHandler:(UISwipeGestureRecognizer *)gesture {
    switch (gesture.direction) {
        case UISwipeGestureRecognizerDirectionLeft: {
            [moviePlayer stop];
            while (self.isCurrentPlayingIndex >= 0) {
                self.isCurrentPlayingIndex --;
                DTModel *msg = [data objectAtIndex:self.isCurrentPlayingIndex];
                NSString *url = msg.path;
                if (![ValidateHelper isHttpHead:url]) {
                    url = [NSString stringWithFormat:@"%@%@",img_Url,url];
                }
                if (url.length > 0) {
                    moviePlayer.contentURL = [NSURL URLWithString:url];
                    break;
                }

            }
            
        }
            break;
        case UISwipeGestureRecognizerDirectionRight: {
            [moviePlayer stop];
            while (self.isCurrentPlayingIndex < data.count) {
                self.isCurrentPlayingIndex ++;
                DTModel *msg = [data objectAtIndex:self.isCurrentPlayingIndex];
                NSString *url = msg.path;
                if (![ValidateHelper isHttpHead:url]) {
                    url = [NSString stringWithFormat:@"%@%@",img_Url,url];
                }
                if (url.length > 0) {
                    moviePlayer.contentURL = [NSURL URLWithString:url];
                    break;
                }
                
            }

        }
            break;
        default:
            break;
    }
}

#pragma mark 图片放大
-(void)EnlargePicAction:(NSMutableArray *)not currentIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray  *imgdata = [[NSMutableArray alloc]init];
//    DTModel *msg = not;
//    for (int i= 0;i<msg.attachment.count; i++) {
//        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
//        NSString *url = [[msg.attachment objectAtIndex:i] objectForKey:@"path"];
//        if (![ValidateHelper isHttpHead:url]) {
//            url = [NSString stringWithFormat:@"%@%@",img_Url,url];
//        }
//        photo.photoURL = [NSURL URLWithString:url];
//        [imgdata addObject:photo];
//    }
    
    
    
    for (DTModel *model in not) {
        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
        NSString *url = model.path;
        //xhw2018-1-18改bug15223之前的第一个+号也算，所以移除第一个，所以加个判定
        if (url) {
            if (![ValidateHelper isHttpHead:url]) {
                url = [NSString stringWithFormat:@"%@%@",img_Url,url];
            }
            if ([url rangeOfString:@"mp4"].location == NSNotFound) {
                photo.photoURL = [NSURL URLWithString:url];
                [imgdata addObject:photo];
            }
        }else {
            
        }
//        if (![ValidateHelper isHttpHead:url]) {
//            url = [NSString stringWithFormat:@"%@%@",img_Url,url];
//        }
//        if ([url rangeOfString:@"mp4"].location == NSNotFound) {
//            photo.photoURL = [NSURL URLWithString:url];
//            [imgdata addObject:photo];
//        }
    }
    
    // 图片游览器
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc] init];
    // 数据源/delegate
    //    pickerBrowser.delegate = self;
    pickerBrowser.status = UIViewAnimationAnimationStatusFade;
    
    // 数据源可以不传，传photos数组 photos<里面是ZLPhotoPickerBrowserPhoto>
    pickerBrowser.photos = imgdata;
    // 是否可以删除照片
    pickerBrowser.editing = NO;
    // 当前选中的值
//    pickerBrowser.currentIndexPath = indexPath;
    pickerBrowser.currentIndexPath = [NSIndexPath indexPathForItem:indexPath.item -1 inSection:0];
    // 展示控制器
    [pickerBrowser showPickerVc:self.mainVC];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backActino:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
   
    CGFloat y = scrollView.contentOffset.y;
    
    NSLog(@"相册移动==：xw --%f",y);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"xwScroll" object:nil userInfo:@{@"key":[NSString stringWithFormat:@"%f",y]}];
    
}

- (AddFileViewController *)addFileVC {
    if (!_addFileVC) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"Dynaminc"
                                                                     bundle:[NSBundle mainBundle]];
        _addFileVC = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFileViewController"];
        //xhw2018-1-15改
//        _addFileVC.InType = 2;
        _addFileVC.InType = 3;
        //xhw10月26号改:
//        _addFileVC.hideVideo = YES;
        _addFileVC.hideVideo = false;
        _addFileVC.delegate = self;
    }
    //xhw2018-1-18改:注释点了下面一句代码，添加了到下括号的代码
//    return _addFileVC;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"Dynaminc"
                                                                 bundle:[NSBundle mainBundle]];
    _addFileVC = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddFileViewController"];
    _addFileVC.InType = 3;
    _addFileVC.hideVideo = false;
    _addFileVC.delegate = self;
    return _addFileVC;
}

#pragma mark - <AddFileVCDelegate>
- (void)didGetImage:(UIImage *)image {
    
    
    [self sendDataToServerWithEditImage:image];
}

- (void)sendDataToServerWithEditImage:(UIImage *)editImage {
    
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];
    
    
    NSMutableArray *imgdata =[[NSMutableArray alloc]init];
    NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
    [dici setObject:@"file" forKey:@"key"];
    [dici setObject:UIImageJPEGRepresentation(editImage, 0.00001) forKey:@"value"];
    [imgdata addObject:dici];
    
    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:addAlbumUrl postParems:dic data:imgdata];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];
    
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
    float progres = progress/total;
    [SVProgressHUD showProgress:progres status:@"请求中..."];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas{
//    NSLog(@"connection.currentRequest.URL.absoluteString:%@", connection.currentRequest.URL.absoluteString);
    NSString *request= [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result = [ValidateHelper jsonStringToDictionary:request];
    int code = [[[result objectForKey:@"state"] objectForKey:@"code"] intValue];
    if ([connection.currentRequest.URL.absoluteString isEqualToString:@"http://yimisns.com/index.php/User/Api/add_album"]) {
        if (code == 0) {
            [SVProgressHUD showSuccessWithStatus:@"发布成功"];
            //创建通知
            dispatch_async(dispatch_get_main_queue(), ^{
                NSNotification *notification = [NSNotification notificationWithName:@"public" object:nil userInfo:nil];
                
                [[NSNotificationCenter defaultCenter] postNotification:notification];
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshData" object:nil userInfo:nil];
            });
            
            [self.mainVC dismissViewControllerAnimated:YES completion:nil];
        } else {
            [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
        }
    } else if ([connection.currentRequest.URL.absoluteString isEqualToString:@"http://yimisns.com/index.php/User/Api/album_delete"]) {
        if (code == 0) {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
//            [data removeObjectAtIndex:_deleteIndexPath.item];
            [data removeObject:_deleteModel];
//            [self.collection deleteItemsAtIndexPaths:@[_deleteIndexPath]];
            [self.collection reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
        }
    }
    
//    if(code == 0){
//        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
//        //把最前面的视图控制器dismiss掉
////        UIViewController *parentVC = self.presentingViewController;
////        UIViewController *bottomVC;
////        while (parentVC) {
////            bottomVC = parentVC;
////            parentVC = parentVC.presentingViewController;
////        }
////        [bottomVC dismissViewControllerAnimated:YES completion:nil];
//        [self dismissViewControllerAnimated:YES completion:nil];
//    }else{
//        [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
//    }
}

@end
